package com.czxy.filter;

import com.czxy.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 在这个过滤器中，进行路径的拦截，
 * 放行的路径：/login、/regist、/logout...
 * 拦截的路径：/student/all、学生修改、学生新增、学生删除...
 * gateway进行权限校验
 */
@Component
public class JWTFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取请求的url
        String url = exchange.getRequest().getURI().getPath();
        //2 判断url是否需要拦截，如果不需要拦截，直接放行
        if (url.contains("/login")||url.contains("/regist")||url.contains("/logout")){
            System.out.println("无需登录，直接放行");
            return chain.filter(exchange);
        }
        //3 如果需要拦截，拦截之后，取出请求头中的token，
        List<String> tokens = exchange.getRequest().getHeaders().get("authorization");
        //4 借助jwt解析token
        if (tokens!=null&&tokens.size()!=0){
            Claims claims = JWTUtil.parseToken(tokens.get(0), "teacher");
            if (claims!=null){
                //5 如果解析成功，放行
                return chain.filter(exchange);
            }
        }
        //6 如果解析失败，则返回401，鉴权失败
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();
    }
}
